﻿#region using statments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

#endregion

namespace PrehistoricGame
{
    public class BackgroundManager
    {
        private SortedSet<Background> backgrounds = new SortedSet<Background>();

        public void addWrappedBackground(Texture2D img, float depth, Vector2 offset)
        {
            addBackground(img, depth, true, offset);
        }

        public void addWrappedBackground(Texture2D img, float depth)
        {
            addWrappedBackground(img, depth, Vector2.Zero);
        }

        public void addNonWrappedBackground(Texture2D img, float depth, Vector2 offset)
        {
            addBackground(img, depth, false, offset);
        }

        public void addNonWrappedBackground(Texture2D img, float depth)
        {
            addNonWrappedBackground(img, depth, Vector2.Zero);
        }

        public void addBackground(Texture2D img, float depth, bool iswrapped, Vector2 offset)
        {
            backgrounds.Add(new Background(img, depth, iswrapped, offset));
        }

#warning TODO: Add options for different Colors and/or SpriteEffects
#warning TODO: Vertical wrap?
        public void Draw(GameTime gameTime, SpriteBatch sb, Vector2 position, Viewport vp)
        {
            foreach (Background bg in backgrounds)
            {
                //A background's position is based on a standard offset + an offsset based on camera focal point and layer depth of the background
                Vector2 bgpos = -bg.Depth * position + bg.Offset;
                
                if (bg.IsWrapped)
                {
                    //Adjust background position to be within screen range
                    int shifts = 0;
                    
                    if (bgpos.X < 0)
                        shifts = (int)bgpos.X / bg.Img.Width;
                    else if (bgpos.X > vp.Width)
                        shifts = ((int)bgpos.X - vp.Width) / bg.Img.Width + 1;

                    bgpos.X += -shifts * bg.Img.Width;

                    //Draw a second time if either left or right side of background is visible
                    if (bgpos.X + bg.Img.Width < vp.Width)
                        sb.Draw(bg.Img, new Vector2(bgpos.X + bg.Img.Width, bgpos.Y), Color.White);
                    else if (bgpos.X > 0)
                        sb.Draw(bg.Img, new Vector2(bgpos.X - bg.Img.Width, bgpos.Y), Color.White);
                }

                //Don't draw if texture is positioned completely outside of the viewport
                if (bgpos.X < vp.Width && bgpos.X + bg.Img.Width > 0)
                {
                    sb.Draw(bg.Img, bgpos, Color.White);
                }
            }
        }
    }
}